package com.songyang.yougnsql.server.serialize;

import com.songyang.yougnsql.common.ErrorMsg;
import com.songyang.yougnsql.common.ExceptionHandler;
import com.songyang.yougnsql.common.YoungSQLException;
import com.songyang.yougnsql.config.Config;
import com.songyang.yougnsql.config.ConfigConst;
import com.songyang.yougnsql.server.serialize.inter.YoungSqlSerialize;

import java.util.HashMap;

/**
 * @ClassName SerializeFactory
 * @Description 序列化工厂
 * @date 2022/12/30 11:46
 * @Author yanceysong
 * @Version 1.0
 */
public class SerializeFactory {
    private static final HashMap<Integer, YoungSqlSerialize> map = new HashMap<>();
    private static int encoderType=YoungSqlEncoder.YOUNG_SERIALIZE;

    static {
        map.put(YoungSqlSerialize.YOUNG_SERIALIZE, new YoungSqlEncoder());
        map.put(YoungSqlSerialize.KRYO_SERIALIZE, new KryoEncoder());
    }

    /**
     * 根据配置文件获取一个编码器
     *
     * @return 编码器
     */
    public static YoungSqlSerialize getEncoder() {
        if (!map.containsKey(encoderType)) {
            try {
                throw new YoungSQLException(ErrorMsg.ILLEGAL_ENCODER_TYPE);
            } catch (YoungSQLException e) {
                ExceptionHandler.handler(e);
            }
        }
        return map.get(encoderType);
    }

    /**
     * 从配置文件获取编码器的结果,默认为自己的编解码器
     */
    public static void init() {
        String getConfig = (String) Config.getConfig(ConfigConst.ENCODER_TYPE);
        encoderType = getConfig != null && getConfig.equals("") ? Integer.parseInt(getConfig) : YoungSqlSerialize.YOUNG_SERIALIZE;
    }
}
